package com.escape.wx.handler;

import com.escape.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author: escape_zebra
 * @CreateTime: 2025-01-16  20:39
 * @Description: 接收用户消息工厂实现类
 * @Version: 1.0
 */
@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxChatMsgHandler{

    private static final String KEY_WORD = "验证码";
    private static final String LOGIN_PREFIX = "loginPrefix";

    @Resource
    private RedisUtil redisUtil;

    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> messageMap) {
        log.info("接收用户消息触发!");
        String toUserName = messageMap.get("ToUserName");
        String fromUserName = messageMap.get("FromUserName");
        String content = messageMap.get("Content");
        if (!KEY_WORD.equals(content)) {
            return "";
        }

        Random random = new Random();
        int code = random.nextInt(1000000);

        String key = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(code));
        redisUtil.setNx(key, fromUserName,5L, TimeUnit.MINUTES);

        return "<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "<CreateTime>1737029098</CreateTime>\n" +
                "<MsgType><![CDATA[text]]></MsgType>\n" +
                "<Content><![CDATA[验证码为："+code+"，请使用验证码登录经典鸡翅平台，感谢支持！可以 v 我50吗？]]></Content>\n" +
                "<MsgId>24868275616129270</MsgId>\n" +
                "</xml>";
    }
}